<?php
/**
 * DirectoryReference refers to a directory on the file system and provides
 * methods for accessing information on directories and manipulating them.
 * 
 * @package be.appcraft.util
 * @version $Revision: 1.1 $
 *
 * @author Stijn Van Bael
 * @since 1.0
 */
class Pageley_Util_Directory extends Pageley_Util_File {

	/**
	 * Constructs a new DirectoryReference
	 *
	 * @param string $path: the absolute path to the directory
	 */
	public function __construct($path) {
		parent::__construct($path);
	}
	
	/**
	 * Gets a list of all files in the directory.
	 * 
	 * @return Map containing the files
	 */
	public function getFiles() {
		if(!$this->exists()) {
            throw new Pageley_Util_IoException("Cannot read non-existing directory '" . $this->getPath() . "'.");
		}
	    $files = new Pageley_Util_ArrayMap();
	    try {
	       $handler = opendir($this->getPath());
	        while ($file = readdir($handler)) {
	            if($file != "." && $file != ".." && $file != "") {
	                $filePath = $this->getPath() . "/" . $file;
	                if(is_dir($filePath)) {
	                    $files->add(new Pageley_Util_Directory($filePath));
	                } else {
	                    $files->add(new Pageley_Util_File($filePath));
	                }
	            }
	        }
	        closedir($handler);
	    } catch(Exception $e) {
	    	throw new Pageley_Util_IoException("Failed to read directory '" . $this->getPath() . "' due to permission restrictions or file system error.", E_WARNING, $e);
	    }
    	return $files;
	}

	public function createDirectory() {
        if($this->exists()) {
            throw new Pageley_Util_IoException("Cannot create directory '" . $this->getPath() . "'. A file or directory with the same name already exists.");
        }
        mkdir($this->getPath(), 0777, true);
    }
}